package com.utils;

import cn.hutool.core.lang.Snowflake;
import com.mc.mcvideo.config.filter.AccessFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Component
public class IdUtil {

    private static Snowflake snowflake;

    private static RedisUtil redisUtil;

    @Autowired
    public void setRedisUtil(RedisUtil redisUtil) {
        com.mc.mcvideo.utils.IdUtil.redisUtil = redisUtil;
    }

    private static final String WORKER_ID_KEY = "mc_video:id:worker_id:key:";

    /**
     * 单机雪花算法
     */
    @PostConstruct
    public void init() {
        Long workerId = redisUtil.incr(WORKER_ID_KEY);
        if (workerId.intValue() > 30) {
            workerId = redisUtil.decrBy(WORKER_ID_KEY, 30L);
        }
        snowflake = new Snowflake(workerId, 10, true);
    }

    /**
     * 获取当前登录米虫id
     * @return
     */
    public String getCurrentUserName() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Object obj = request.getAttribute("username");
        if (Objects.nonNull(obj)) {
            return obj.toString();
        }
        return null;
    }

    /**
     * 获取当前登录验证token
     * @return
     */
    public String getCurrentAuth() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Object obj = request.getHeader(AccessFilter.HERDER_AUTHORIZATION);
        if (Objects.nonNull(obj)) {
            return obj.toString();
        }
        return null;
    }

    /**
     * 获取当前登录验证token
     * @return
     */
    public String getCurrentUnionId() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Object obj = request.getAttribute("unionId");
        if (Objects.nonNull(obj)) {
            return obj.toString();
        }
        return null;
    }

    /**
     * 获取当前登录身份
     * @return
     */
    public String getCurrentRole() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Object obj = request.getAttribute("role");
        if (Objects.nonNull(obj)) {
            return obj.toString();
        }
        return null;
    }

    public Long getNextId() {
        return snowflake.nextId();
    }

}
